<?php

namespace App\Http\Controllers\Api\V1;
use App\Models\GcUserImage;
use App\Models\GcGptImage;
use App\Models\GcSensitive;
use Illuminate\Support\Facades\Cache;
use Brick\Math\RoundingMode;
use App\Http\Controllers\Api\V1\Resources\GcUserImagesResource;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;

class GcImageTestController extends Controller
{
	
	public function index()
	{ 
		$user = request()->user();
		$gcType = request('gc_type');
		if(empty($gcType)){

			fail('请传入渠道字段！');
		}
		$result  = $user->GcUserImage()->where("gc_type",$gcType)->orderByDesc('id')->paginate();/*->where(function (Builder $query) {
				$query->whereDate('used_at', Carbon::today())
				->orWhere('is_used', false);
		})->orderByDesc('id')->paginate();*/
		
		return GcUserImagesResource::collection($result);
	}


	public function store()
	{

		$lock = Cache::lock('use_image', 10);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');
			$gcId = request('gc_id');
			if(empty($gcId)){

				fail('请传入图文下载ID');
			}

			$update = ['is_used'=>true,"used_at"=>Carbon::now()];
			request()->user()->GcUserImage()->where("id",$gcId)->update($update);
		

		} finally {
			$lock->release();
		}

		return response(null, 204);
	}
	

	public function change()
	{

		$lock = Cache::lock('change_test', 10);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');
			$gcId = request('gc_id');
			if(empty($gcId)){

				fail('请传入图文下载ID');
			}

			$updateData = [];
			$gcContent = GcUserImage::find($gcId);
			
			if($gcContent->change_num > 1){

				fail('当前文案更换次数已达上限！');
			}

			$sensitives  = GcSensitive::where("gc_type",$gcContent->gc_type)->get()->toArray();
			$str = "";
			if($sensitives){

				$sensitiveArr = array_column($sensitives,"name");
				$str = implode(',',$sensitiveArr);
				
			}

			$titleData = [
			    'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是文案编辑工作者"],
			        ['role' => 'user', 'content' => '请将标题【'.$gcContent->title_main.'】按照小红书的说话方式重新总结一个标题，限制20个字内'],
			    ],
			    'max_tokens' => 1000
			];

			if($str){
				$titleData = [
				    'model' => 'gpt-3.5-turbo',
				    'messages' => [
				    	['role' => 'system', "content"=> "你是文案编辑工作者"],
				        ['role' => 'user', 'content' => '请将标题【'.$gcContent->title_main.'】按照小红书的说话方式重新总结一个标题并且不能包含敏感词【'.$str.'】，限制20个字内'],
				    ],
				    'max_tokens' => 1000
				];

			}

			
			
			$titleResult = $this->curl($titleData);
			
			$titleResult = json_decode($titleResult,true);
			$title = "";
			if($titleResult['choices']){

				$title = $titleResult['choices'][0]['message']['content'];

				if($sensitives){
					foreach($sensitives as $v){
						if(strstr($title,$v['name'])){

							$title = substr_replace($v['name'], $v['sub_words'], $title);
						}

					}
				}	

				$updateData['title_gpt'] = $title;
			}


			$data = [
			    'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是文案编辑工作者"],
			        ['role' => 'user', 'content' => '请将内容【'.$gcContent->content_main.'】按照口语方式重新总结一段文案，内容为中文，不超过500字，保留emoji，去掉html标签'],
			    ]
			];

			if($str){
				$data = [
				    'model' => 'gpt-3.5-turbo',
				    'messages' => [
				    	['role' => 'system', "content"=> "你是文案编辑工作者"],
				        ['role' => 'user', 'content' => '请将内容【'.$gcContent->content_main.'】按照口语方式重新总结一段文案，内容为中文，不超过500字并且不能包含敏感词【'.$str.'】，保留emoji，去掉html标'],
				    ]
				];


			}

			
			$result = $this->curl($data);
			
			$result = json_decode($result,true);
			
			$content = "";
			if($result['choices']){

				$content = $result['choices'][0]['message']['content'];
				if($sensitives){
					foreach($sensitives as $v){
						if(strstr($content,$v['name'])){

							$content = str_replace($v['name'], $v['sub_words'], $content);
						}

					}
				}	

				$updateData['content_gpt'] = $content;
			}

			if(empty($updateData)){
				fail('gpt账号余额不足，无法生成！');

			}
			$update['change_num'] = $gcContent->change_num + 1;
			$updateData['gc_user_image_id'] = $gcId;
			request()->user()->GcUserImage()->where("id",$gcId)->update($update);
			GcGptImage::create($updateData);
		} finally {
			$lock->release();
		}

		return response(null, 204);
	}

	public function curl($data){

		$curl = curl_init();
		$data = json_encode($data);


		curl_setopt_array($curl, array(
		   CURLOPT_URL => 'https://api.chatanywhere.com.cn/v1/chat/completions',
		   CURLOPT_RETURNTRANSFER => true,
		   CURLOPT_ENCODING => '',
		   CURLOPT_MAXREDIRS => 10,
		   CURLOPT_TIMEOUT => 0,
		   CURLOPT_FOLLOWLOCATION => true,
		   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		   CURLOPT_CUSTOMREQUEST => 'POST',
		   CURLOPT_POSTFIELDS =>$data,
		   CURLOPT_HTTPHEADER => array(
		      'Authorization: Bearer '.env('CHATGPT_API_KEY'),
		      'User-Agent: Apifox/1.0.0 (https://apifox.com)',
		      'Content-Type: application/json'
		   ),
		));
	   $response = curl_exec($curl);
	   return $response;
	}


	public function sensitive()
	{ 
		$user = request()->user();
		$gcType = request('gc_type');
		if(empty($gcType)){

			fail('请传入渠道字段！');
		}
		$result  = GcSensitive::where("gc_type",$gcType)->get();
		
		return response()->json($result);
	}
}
